<!DOCTYPE html>
<html>
<title>Registration Page :: DIF233 - Unit 1 - Excercise 2</title>
<body>
	<?php
		$first_name="";
		$last_name="";
		$mobile_number="";
		$email_id="";
		function get_connection(){
			$file = fopen("config.txt","r+") or exit("Sorry not able to open the register file");
			$line = fgets($file);
			$value = explode(":", $line);
			$connection = mysqli_connect($value[0], $value[1], $value[2], $value[3]);
			
			if(mysqli_connect_errno($connection)){
				echo "unable to connect to test data base";
				exit("unable to connect to test data base");
			}else{
				return $connection;
			}
		}
		if(!empty($_POST["Update"])){
			$connection = get_connection();
			$update_details = "update user_profile set user_firstname = '".$_POST['first_name']."', user_lastname = '".$_POST['last_name']."', mobile_number = '".$_POST['mobile_number']."',email_id = '".$_POST['email_id']."' where user_id = ".$_POST["id"];
			echo $update_details;
			if(!mysqli_query($connection, $update_details)){
				echo "<h3>Failed to update due to : </h3>".mysqli_error($connection);
				header("Location: profile.php?id=".$_POST["id"]);
				exit();
			}else{
				header("Location: user.php?profile=updated&id=".$_POST["id"]);
				exit();
			}
			mysqli_close($connection);
		}else{
			$connection = get_connection();
			$get_details = "select user_firstname, user_lastname, mobile_number,email_id from user_profile where user_id = '".$_GET["id"]."'";
			$result = mysqli_query($connection, $get_details);
			$row = mysqli_fetch_array($result);
			$first_name = $row["user_firstname"];
			$last_name = $row["user_lastname"];
			$mobile_number = $row["mobile_number"];
			$email_id = $row["email_id"];
			mysqli_close($connection);
		}	
	?>
<form method="post" name="register" action="profile.php?id=<?php echo $_GET['id'] ?>">
<input type="hidden" name="id" value=<?php echo empty($_GET["id"])?$_POST["id"]:$_GET["id"]?> />
	<table border="0" width="100%">
		<tr>
			<td>
				First Name:
			</td>
			<td>
				<input type="text" name="first_name" value="<?php echo $first_name ?>" required/>
			</td>
		</tr>
		<tr>
			<td>
				Last Name:
			</td>
			<td>
				<input type="text" name="last_name" value="<?php echo $last_name ?>" required/>
			</td>
		</tr>
		<tr>
			<td>
				Mobile Number:
			</td>
			<td>
				<input type="text" name="mobile_number" value="<?php echo $mobile_number ?>" required/>
			</td>
		</tr>		
		<tr>
			<td>
				Email Id:
			</td>
			<td>
				<input type="email" name="email_id" value="<?php echo $email_id ?>" required/>
			</td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" name="Update" value="Update"/></td>
		</tr>		
	</table>
</form>
</body>
</html>
